#
# Copyright (C) [2024] Xingyun Integrated Circuit, Inc.
#
# GreenCode was a private technology asset of Xingyun Integrated Circuit， Inc （Confidential）
# Author: Shawn.Tan
# Date: 2025.10.28
#
# History: Initial Version 2025.10.28
#
#
from PageFaultSequence import PageFaultSequence
from base.ChoicesModifier import ChoicesModifier
from gpgpu.EnvGPGPU import EnvGPGPU
from gpgpu.GenThreadGPGPU import GenThreadGPGPU
from gpgpu.ModifierUtils import PageFaultModifier


#  This test verifies recovery from a page fault on a branch operation.
class MainSequence(PageFaultSequence):
    def __init__(self, gen_thread, name=None):
        super().__init__(gen_thread, name)
        self._mInstrList = ("JAL##CALM", "JALR##CALM")
        self._mExceptionCodes = [12]
        self._mExceptionSubCodes = {}  # no sub-codes for gpgpu

    # Create an instance of the appropriate page fault modifier.
    def createPageFaultModifier(self):
        return PageFaultModifier(self.genThread, self.getGlobalState("AppRegisterWidth"))

    # Create a list of instructions to choose from to trigger a page fault.
    def getInstructionList(self):
        return self._mInstrList

    # Return exception codes.
    def getExceptionCodes(self):
        return self._mExceptionCodes


def gen_thread_initialization(gen_thread):
    (delegate_opt, valid) = gen_thread.getOption("DelegateExceptions")
    if valid and delegate_opt == 1:
        # enable exception delegation for some portion of the generated tests.
        delegation_enables = ChoicesModifier(gen_thread)
        weightDict = {"0x0": 0, "0x1": 50}
        delegation_enables.modifyRegisterFieldValueChoices(
            "medeleg.Instruction page fault", weightDict
        )
        delegation_enables.commitSet()


GenThreadInitialization = gen_thread_initialization
MainSequenceClass = MainSequence
GenThreadClass = GenThreadGPGPU
EnvClass = EnvGPGPU
